package server

import (
	"github.com/gin-gonic/gin"
	"go_server/login_server/dao/server_list_dao"
	"go_server/login_server/initializer/config_init"
	"go_server/zinx/zlog"
	"go_server/zinx/zutils"
	"net/http"
	"time"
)

type responseServer struct {
	Address   string `json:"address"`
	Name      string `json:"name"`
	Status    uint8  `json:"status"`
	Id        int    `json:"id"`
	Recommend bool   `json:"recommend"`
}

type serverListRequest struct {
	Uid string `json:"uid"`
}

type serverListResponse struct {
	ResList []responseServer `json:"resList"`
	Token   string           `json:"token"`
}

func GetServerList(ctx *gin.Context) {
	//todo 考虑是否做必要的验证
	var request serverListRequest
	if err := ctx.ShouldBindJSON(&request); err != nil {
		zlog.Errorf("GetServerList bind request param failed: %s", err)
		ctx.String(http.StatusBadRequest, "获取参数失败")
		return
	}

	uid := request.Uid

	if len(uid) < 0 {
		ctx.String(http.StatusBadRequest, "未能获取到UID参数")
	}
	header := zutils.DefaultHeader
	payload := zutils.JwtPayLoad{
		Issue:       "login",
		IssueAt:     time.Now().Unix(),
		Expireation: time.Now().Add(24 * time.Hour).Unix(),
		UserDefined: map[string]any{"uid": uid},
	}

	configViper := config_init.GetConfigViper()
	secret := configViper.GetString("secret")

	if token, err := zutils.GenJWT(header, payload, secret); err != nil {
		zlog.Errorf("生成token失败：%s", err)
		ctx.JSON(http.StatusInternalServerError, serverListResponse{nil, ""})
	} else {
		serverList := server_list_dao.GetServerList()
		resList := make([]responseServer, 0, len(serverList))
		for _, serverObj := range serverList {
			if serverObj.Used != 1 {
				continue
			}

			server := responseServer{
				Address: serverObj.Address,
				Name:    serverObj.Name,
				Status:  serverObj.Status,
				Id:      serverObj.Id,
			}
			if serverObj.Recommend == 1 {
				server.Recommend = true
			} else {
				server.Recommend = false
			}

			resList = append(resList, server)
		}
		ctx.JSON(http.StatusOK, serverListResponse{resList, token})
	}
}
